package com.industry.system.utils;

import com.industry.system.controller.vo.MenuRespVO;
import com.industry.system.controller.vo.MenuTreeRespVO;
import com.industry.system.convert.MenuConvert;
import com.industry.system.dal.dataobject.SystemMenu;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SystemMenuUtils {

    //加载children
    public static List<MenuTreeRespVO> listTreeMenus(List<SystemMenu> menus , String rootId) {
        MenuTreeRespVO root = new MenuTreeRespVO();
        root.setId(rootId);
        convertTree(menus, root);
        return root.getChildren();
    }
    //deep
    public static void convertTree(List<SystemMenu> menus, MenuTreeRespVO root) {
        List<MenuTreeRespVO> children = menus.stream()
                .filter(m -> m.getParentId().equals(root.getId()))
                .map(MenuConvert.INSTANCE::convertTreeBase)
                .toList();
        root.setChildren(children);
        children.forEach(c -> convertTree(menus, c));
    }

    //构造菜单数据 ，key：模块。value 菜单树
    public static Map<String,List<MenuTreeRespVO>> menuTreeBuilder(List<SystemMenu> systemMenus){
        List<SystemMenu> menus = systemMenus.stream()
                .filter(i -> i.getMenuType() != null
                        && !StringUtils.equals("M", i.getMenuType()) && i.getModuleKey() != null)
                .collect(Collectors.toList());
        if(CollectionUtils.isEmpty(menus)){
            return new HashMap<>();
        }
        Map<String,String> moduleMap = systemMenus.stream()
                .filter(i -> i.getMenuType() != null && StringUtils.equals("M", i.getMenuType()) && i.getModuleKey() != null)
                .collect(Collectors.toList()).stream()
                    .collect(Collectors.toMap(SystemMenu::getModuleKey,SystemMenu::getId));
        //get root（module）
        Map<String, List<SystemMenu>> collect = menus.stream().collect(Collectors.groupingBy(SystemMenu::getModuleKey));
        Map<String,List<MenuTreeRespVO>> resMap = new HashMap<>();
        collect.forEach((k,v)-> resMap.put(k,listTreeMenus(v,moduleMap.get(k))));
        return resMap;
    }

    //构造模块列表数据
    public static List<MenuRespVO> moduleInfoBuilder(List<SystemMenu> systemMenus){
        if(CollectionUtils.isEmpty(systemMenus)){
            return new ArrayList<>();
        }
        List<SystemMenu> sysModule = systemMenus.stream().filter(i->
                StringUtils.equals("M",i.getMenuType()) && !StringUtils.isEmpty(i.getModuleKey())
        ).collect(Collectors.toList());
        return MenuConvert.INSTANCE.convertList(sysModule);
    }

}
